#encoding:utf-8
'''
FileName:channelsync.py
Creator:王烨
Date:2010.5.23
'''
import socket
import struct

import channel
from error import *

class ChannelSync(channel.Channel):
    def __init__(self):
        channel.Channel.__init__(self)
        self.socket = None
    
    def Connect(self, addr):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect(addr)
        
    def Close(self):
        self.socket.close()
        
    def __SendString( self, buffer ):
        networkOrderBufferLen = struct.pack("!I", len(buffer))
    
        buffer = networkOrderBufferLen + buffer
        bytesSent = 0
        while bytesSent < len(buffer):
            sent = self.socket.send(buffer[bytesSent:])
            if sent == 0:
                    raise ProtobufError(IO_ERROR, "socket connection broken")
            bytesSent += sent
        
    def CallMethod(self, methodDescriptor, controller, parameters, resultClass, done = None):
        '''执行RPC'''
        print '开始执行RPC'
        (uuid ,request) = self.SerializeParameters(methodDescriptor, parameters)
        self.__SendString(request)
        print '发送请求完毕'
        
        buffer = self.socket.recv( struct.calcsize( "!I" ) )
        bufferLen = int( struct.unpack( "!I", buffer )[0] )
        buffer = self.socket.recv( bufferLen )
        response = self.DeserializeResponse(buffer)
        if response.uuid == uuid:
            result = self.DeserializeResult(response, resultClass, controller)
            if done == None:
                return result
            else:
                done(result)
        else:
            raise ProtobufError(BAD_RESPONSE_PROTOCOL, '无效的响应uuid')